layui.define(['jquery'], function (exports) {
  var $ = layui.jquery;
  var checkData = {};

  const layFilter = {
    dataSource: {},
    render: function (options) {
      
      const {elem, dataSource} = options;
      this.dataSource = dataSource;
      const $dom = $(elem);
      var that = this;

      var filter = {
        //获取选中值
        getValue: function (callback) {
          var obj = getSelectedData($dom,dataSource);
          if(callback && typeof callback === 'function'){
            callback.call(this, obj);
          }else{
            return obj
          }
        },
        setValue:function(name,...value){
          const { dataSource } = that;
          $dom.find(`.lay-filter-item[data-value="${name}"]`).each(function(){
            $(this).find('.lay-filter-right .lay-filter-right-item').each(function(){
              if(value.indexOf(`${$(this).data('value')}`) >= 0){
                $(this).click();
              }
            })
          })
        },
        setDisabled: function (name,...value) {
          const { dataSource } = that;
          $dom.find(`.lay-filter-item[data-value="${name}"]`).each(function(){
            $(this).find('.lay-filter-right .lay-filter-right-item').each(function(){
              if(value.indexOf(`${$(this).data('value')}`) >= 0){
                $(this).removeClass('active');
                $(this).addClass('layui-disabled')
                dataSource.forEach((o,i)=>{
                  if(o.name === name){
                    const { data } = o;
                    data.forEach((s,j) => {
                      if(value.indexOf(s.value) >= 0){
                        layFilter.dataSource[i].data[j].disabled = true;
                      }
                    })
                  }
                })
              }
            })
          })
        },
        resetFilter: function (callback,...names) {
          const $doms = $dom.find(`.lay-filter-item`);
          if(names && names.length > 0){
            $doms.each(function(){
              if(names.indexOf($(this).data('value')) >= 0){
                $(this).find('.active').removeClass('active');
              }
            })
          }else{
            $doms.find('.active').removeClass('active');
          }
          callback.call();
        },
        on: function (filter, callback) {
          var f = filter.substring(0, filter.indexOf('('));
          var e = filter.substring(filter.indexOf('(') + 1, filter.length - 1);
          if (typeof callback === "function") {
            $("[lay-filter='" + e + "']").on(f, function () {
              var obj = getSelectedData($dom,dataSource);
              callback.call(this, obj);
            });
          } else {
            throw Error('param is not a function');
          }
        }
      }
      initHandle(options,filter);
      return filter;
    }
  }

  const initHandle = (options,filter) => {
    var { elem, labelWidth=100, itemWidth, color="#009688", dataSource ,success= function(){}, onChange=function(){}} = options;
    if( !dataSource ){
      throw Error("dataSource is null or empty")
    }
    var hasItemWidth = false;
    labelWidth = typeof labelWidth === 'number' ? `${labelWidth}px` : labelWidth;
    if(itemWidth){
      hasItemWidth = true;
        if(typeof itemWidth !== 'object'){
          let arr = [];
          dataSource.forEach(o=>{
            arr.push(itemWidth)
          })
          itemWidth = arr;
        }
    } 
    var $dom = $(elem);
    var $layFilterContent = $(`<div class="lay-filter-content"></div>`);
    dataSource.forEach((item,i) => {
      const { data = [], name:itemName, title, type = 'radio', allValue, allName = '全部' } = item;
      if(isEmpty(itemName) || isEmpty(title)){
        return;
      }
      var $item = $(`<div class="lay-filter-item" data-value="${itemName}"></div`);
      var $label = $(`<div class="lay-filter-label" style="width:${labelWidth}">${title}:</div>`);
      var $filterRight = $(`<div class="lay-filter-right"></div>`)
      let currentItemWidth = null;
      if(hasItemWidth){
        currentItemWidth = i < itemWidth.length ? (typeof itemWidth[i] === 'number' ? `${itemWidth[i]}px`: itemWidth[i]) : '100px';
      }
      var itemList = [];
      let values = [];
      data.forEach(o => {
        const { name, value} = o;
        if(isEmpty(name) || isEmpty(value)){
          return
        }
        var $filter_item = $(`<div class="lay-filter-right-item ${o.disabled ? 'layui-disabled':''}" ${currentItemWidth ? 'style="min-width:' + currentItemWidth +'"':''} data-value="${value}">${name}</div>`);
        $filterRight.append($filter_item);
        
        if(values.indexOf(value) > 0){
          console.warn(`value ${o.value} is repeated`)
        }else{
          values.push(value)
        }
        $filter_item.on('click',()=>{
          const { disabled = false } = o;
          if(disabled || $filter_item.hasClass('layui-disabled')){
            return;
          }
          if(type !== 'checkbox'){
            $filter_item.siblings().removeClass('active')
          }
          $filter_item.toggleClass('active')
          if($filter_item.hasClass('active')){
            //选中
            const count = $filter_item.siblings(".lay-filter-right-item.active").length;
            const disabled_count = data.filter(s => s.disabled).length;
            if(count + disabled_count + 1 === data.length){
              $filter_item.siblings().eq(0).addClass('active')
            }
            onChange.call(this,true,{...item,...{data:o}},$filter_item);
          }else{
            //取消
            $filter_item.siblings().eq(0).removeClass('active');
            onChange.call(this,false,{...item,...{data:o}},$filter_item);
          }
          $filter_item[0].style.setProperty('--color',color)
        });
        
      });
      if(type === 'checkbox'){
        var $all = $(`<div class="lay-filter-right-all" ${currentItemWidth ? 'style="width:' + currentItemWidth +'"':''} data-value="${allValue}">${allName}</div>`);
        $all[0].style.setProperty('--color',color)
        $filterRight.prepend($all);
        $all.on('click',()=>{
          $all.toggleClass('active');
          data.forEach(o=>{
            const { disabled = false } = o;
            var $dom = $filterRight.find(`[data-value="${o.value}"]`);
            if(disabled || $dom.hasClass('layui-disabled')){
              return;
            }
            $dom[$all.hasClass('active') ? 'addClass':'removeClass']('active')
            $dom[0].style.setProperty('--color',color);
          })
        })
      }
      $item.append($label);
      $item.append($filterRight);
      $layFilterContent.append($item);
    });
    $dom.append($layFilterContent);
    success.call(this,filter);
  }

  const getSelectedData = (dom,dataSource)=>{
    const $doms = dom.find('.lay-filter-item');
    let result = {
    }
    
    for(let i = 0; i < $doms.length; i++){
      let $dom = $doms.eq(i);
      const name = $dom.data('value');
      if(!name){
        continue;
      }
      const currentData = getCurrentData(name,dataSource);
      const {type = 'radio'} = currentData;
      if(type === 'checkbox'){
        //多选
        const $all = $dom.find('.lay-filter-right .lay-filter-right-all.active');
        if($all.length > 0){
          //全选了
          if(currentData.allValue){
            result[name] = [currentData.allValue]
          }else{
            result[name] = [];
            $dom.find('.lay-filter-right .lay-filter-right-item.active').each(function(){
              result[name].push(`${$(this).data('value')}`)
            })
          }
        }else{
          //未全选
          result[name] = [];
          $dom.find('.lay-filter-right .lay-filter-right-item.active').each(function(){
            result[name].push(`${$(this).data('value')}`)
          });
        }
      }else{
        //单选
        result[name] = "";
        $dom.find('.lay-filter-right .lay-filter-right-item.active').each(function(){
          result[name] = `${$(this).data('value')}`
        })
      }
    }

    return result
  }

  function getCurrentData(name,dataSource){
    const datas = dataSource.filter(o=> o.name === name);
    if(datas && datas.length > 0){
      return datas[0];
    }
  }

  function isEmpty(v) {
    switch (typeof v) {
    case 'undefined':
        return true;
    case 'string':
        if (v.replace(/(^[ \t\n\r]*)|([ \t\n\r]*$)/g, '').length == 0) return true;
        break;
    case 'boolean':
        if (!v) return true;
        break;
    case 'number':
        if (0 === v || isNaN(v)) return true;
        break;
    case 'object':
        if (null === v || v.length === 0) return true;
        for (var i in v) {
            return false;
        }
        return true;
    }
    return false;
}


  layui.link(layui.cache.base + 'layFilter/layFilter.css');

  exports('layFilter', layFilter);

})